/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package com.mall.common.utils;


import com.mall.common.enums.IEnum;
import org.apache.http.HttpStatus;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 返回数据
 *
 * @author Mark sunlightcs@gmail.com
 */
public class BaseResult extends HashMap<String, Object> implements Serializable {
    private static final long serialVersionUID = 1L;

    public static final String RESULT_CODE = "code";
    public static final String RESULT_MESSAGE = "msg";
    public static final String RESULT_DATA = "data";
    public static final String RESULT_PAGE = "page";


    public BaseResult() {
        put(RESULT_CODE, 0);
        put(RESULT_MESSAGE, "success");
    }

    public static BaseResult error() {
        return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常，请联系管理员");
    }

    public static BaseResult error(String msg) {
        return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
    }

    public static BaseResult error(int code, String msg) {
        BaseResult result = new BaseResult();
        result.put(RESULT_CODE, code);
        result.put(RESULT_MESSAGE, msg);
        return result;
    }

    public static BaseResult error(IEnum iEnum) {
        BaseResult result = new BaseResult();
        result.put(RESULT_CODE, iEnum.code());
        result.put(RESULT_MESSAGE, iEnum.val());
        return result;
    }

    public static BaseResult ok(String msg) {
        BaseResult result = new BaseResult();
        result.put(RESULT_MESSAGE, msg);
        return result;
    }

    public static BaseResult ok(Map<String, Object> map) {
        BaseResult result = new BaseResult();
        result.putAll(map);
        return result;
    }

    public static BaseResult ok() {
        return new BaseResult();
    }

    public BaseResult put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    public static BaseResult isOk(Object data) {
        return putData(data);
    }

    public static BaseResult success(Object data) {
        return putData(data);
    }

    public static BaseResult success() {
        return putData(null);
    }


    public static BaseResult fail(int code, String msg) {
        BaseResult result = new BaseResult();
        result.put(RESULT_CODE, code);
        result.put(RESULT_MESSAGE, msg);
        return result;
    }



    public static BaseResult putData(Object value) {
        return BaseResult.ok().put(BaseResult.RESULT_DATA,value);
    }


    public static BaseResult putPageResult(Object value) {
        return BaseResult.ok().put(BaseResult.RESULT_PAGE,value);
    }


    public Integer getCode(){
        return (Integer)this.get(RESULT_CODE);
    }

    public boolean isOk(){
        if(this.getCode().intValue() == 0){
            return true;
        }else {
            return false;
        }
    }
}
